//
//  ToastView.swift
//  
//
//  Created by tank on 2021/12/5.
//

import Foundation
import SwiftMessages
import SnapKit
import UIKit

class ToastView: BaseView, Identifiable, AccessibleMessage {
    let id: String = UUID().uuidString

    var accessibilityMessage: String?

    var accessibilityElement: NSObject?

    var additionalAccessibilityElements: [NSObject]?

    let type: Toast.ToastType?

    var iconView: UIView?
    
    let contentView: UIView

    init(type: Toast.ToastType? = nil, message: String) {
        self.type = type
        contentView = UIView()
        super.init(frame: .zero)

        backgroundView = contentView

        contentView.layer.masksToBounds = true
        contentView.layer.cornerRadius = 8
        contentView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.8)
        addSubview(contentView)
        
        if type == .loading {
            let loadView = UIActivityIndicatorView(style: .whiteLarge)
            loadView.startAnimating()
            contentView.addSubview(loadView)
            iconView = loadView
        }
        

        let textLabel = UILabel()
        textLabel.text = message
        textLabel.font = UIFont.systemFont(ofSize: 14)
        textLabel.textColor = .white
        contentView.addSubview(textLabel)

        let topView = UIView()
        contentView.addSubview(topView)

        let bottomView = UIView()
        contentView.addSubview(bottomView)

        topView.snp.makeConstraints { make in
            make.height.greaterThanOrEqualTo(0)
            make.height.equalTo(bottomView.snp.height)
            make.top.equalToSuperview()
            make.width.equalToSuperview()
        }
        
        if let iconView = iconView {
            iconView.snp.makeConstraints { make in
                make.centerX.equalToSuperview()
                make.top.equalTo(topView.snp.bottom)
            }
        }
        

        textLabel.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            if let iconView = iconView {
                make.top.equalTo(iconView.snp.bottom).offset(10)
            } else {
                make.top.equalTo(topView.snp.bottom)
                make.left.equalToSuperview().offset(6)
                make.right.equalToSuperview().offset(-6)
            }
        }

        bottomView.snp.makeConstraints { make in
            make.height.greaterThanOrEqualTo(0)
            make.top.equalTo(textLabel.snp.bottomMargin)
            make.bottom.equalToSuperview()
            make.width.equalToSuperview()
        }

        contentView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            
            if iconView != nil {
                make.width.height.greaterThanOrEqualTo(120)
            } else {
                make.height.equalTo(60)
            }
        }
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
